<?
/**
*携程对接
*2015-04-30 
*by pzp
*TicketSenicSpotInfo->[ScenicSpotList]->[ID] 是景区ID
*TicketSenicSpotInfo->[ScenicSpotList]->[ProductList]->[ProductBasicInfo]->[ID] 是产品ID
*TicketSenicSpotInfo->[ScenicSpotList]->[ProductList]->[ResourceList]->[ID] 是资源ID
**/
class Ctrip{

	private $post_array = array(
		'AllianceID'=> 22666, //联盟id
		'SID'=>456827, //站点id 
		'APIKey'=>'899480A9-2747-4F61-A0F2-17302A82B187',// 密钥
		'reqUri' =>'http://openapi.ctrip.com/vacations/OpenServer.ashx',
		'ProtocolType'=>1, //0是xml，1是json
	);
	
	//3.1查询门票景点列表
	public function TicketSenicSpotSearch($Keyword){
		$this->post_array['RequestType']="TicketSenicSpotSearch"; 
		$reqJson=<<<H
{
    "DistributionChannel": 9, 
    "PagingParameter": {
        "PageIndex": 1, 
        "PageSize": 10
    }, 
    "SearchParameter": {
        "Keyword": "$Keyword", 
        "SaleCityID": 2, 
    }
}
H;
		$time = time();
		$this->post_array['reqJson'] = str_replace('"','\"',$reqJson);
		$this->post_array['signature'] = $this->sign($time,$this->post_array['RequestType']);
		$Ctrip_RequestData = $this->Ctrip_RequestData($time,$this->post_array);
		foreach($Ctrip_RequestData['ScenicSpotListItemList'] as $productid){
			$productids[] = $productid['ID'];
		}
		return $productids;
		// print_r($Ctrip_RequestData);
		// return $Ctrip_RequestData;
	} 
	
	//请求接口服务的名称:门票景点详情
	public function TicketSenicSpotInfo($productid){
		$this->post_array['RequestType']="TicketSenicSpotInfo"; 
		$reqJson=<<<H
{
    "DistributionChannel": 9, 
    "ResponseDataType": 0, 
    "ID": [
      107566
    ], 
    "ProductId": null, 
    "DebugKey": null, 
    "ImageSize": null
}
H;
		$time = time();
		$this->post_array['reqJson'] = str_replace('"','\"',$reqJson);
		$this->post_array['signature'] = $this->sign($time,$this->post_array['RequestType']);
		$Ctrip_RequestData = $this->Ctrip_RequestData($time,$this->post_array);
		// return $Ctrip_RequestData ;
		$C_ids = array();
		$C_ids2 = array();
		$C_rids = array();
		$C_Pin = array();
		$C_Pins = array();
		foreach($Ctrip_RequestData['ScenicSpotList'] as $S){
			$C_ids['C_Lid']=$S['ID'];  //景点id
			$C_ids['C_Address']=$S['Address']; //景点地址
			$C_ids['C_Star']=$S['Star']; //景点星级
			$C_ids['C_Image']=$S['Image']; //景点图片
			$C_ids['C_Name']=$S['Name']; //景点名称
			$C_ids['C_OpenTimeDesc']=$S['OpenTimeDesc']; //景点营业时间
			foreach($S['ProductList'] as $Ps){
				if($Ps){
					$C_Pins= array();
					// $deac = array();
					foreach($Ps['ProductAddInfoList'] as $Pin){
						$deac = '';
						foreach($Pin['ProductAddInfoDetailList'] as $Pin2){
							$deac.= $Pin2['DescDetail'];
						}	
						$C_Pins[]=$Pin['AddInfoSubTitleName'].":".$deac;
					}
					$C_ids['C_Pid'] = $Ps['ProductBasicInfo']['ID'];  //产品id
					$C_ids['C_Price']=$Ps['ProductBasicInfo']['Price']; //携程卖价
					$C_ids['C_MarketPrice'] = $Ps['ProductBasicInfo']['MarketPrice'];//市场价
					$C_ids['C_PaymentType'] = $Ps['ProductBasicInfo']['PaymentType'];//支付方式
					$C_ids['C_PayMode'] = $Ps['ProductBasicInfo']['PayMode'];//收款方式			
					$C_ids['C_SaleMode'] = $Ps['ProductBasicInfo']['SaleMode'];//销售方式
					$C_ids['C_ReturnCashAmount'] = $Ps['ProductBasicInfo']['ReturnCashAmount'];//返现金额
					$C_ids['C_AdvanceBookingDays'] = $Ps['AdvanceBookingDays'];  //提前预定天数
					$C_ids['C_AdvanceBookingTime'] = $Ps['AdvanceBookingTime'];  //提前预定时间
					$C_ids['C_CanBookingFirstDate'] = $Ps['CanBookingFirstDate'];  //最早可订时间
					$C_ids['C_ProductDescriptionInfo'] = $Ps['ProductDescriptionInfo']['Introduction'];//产品描述信息
					$C_ids['C_CanBookingFirstDate'] = $Ps['CanBookingFirstDate'];  //最早可订时间
					$C_ids['C_Pdetail'] = $C_Pins;  //预定须知
					$C_ids['C_ResourceList'] = array();
					foreach($Ps['ResourceList'] as $R){
						$C_ids['C_ResourceList'][$R['ID']]['Rid']=$R['ID'];//资源id	
						$C_ids['C_ResourceList'][$R['ID']]['Name']= $R['Name'];//门票资源名称
						$C_ids['C_ResourceList'][$R['ID']]['RealNameType']= $R['RealNameType'];//实名制类型 :0, 不考虑实名验证 1，需要实名制验
						$C_ids['C_ResourceList'][$R['ID']]['PayMode']= $R['PayMode'];//门票支付方式
						$C_ids['C_ResourceList'][$R['ID']]['AdvanceBookingDays']= $R['AdvanceBookingDays'];//资源提前预定天数
						$C_ids['C_ResourceList'][$R['ID']]['AdvanceBookingTime']= $R['AdvanceBookingTime'];//资源提前预定时间
						$C_ids['C_ResourceList'][$R['ID']]['CanBookingLimitTime']= $R['CanBookingLimitTime'];//可预定限制时间
						$C_ids['C_ResourceList'][$R['ID']]['Description']= $R['Description'];//门票资源描述
						$C_ids['C_ResourceList'][$R['ID']]['ExchangeMode']= $R['ExchangeMode'];//门票兑换方式
						$C_ids['C_ResourceList'][$R['ID']]['Price']= $R['Price'];//门票资源携程卖价
						$C_ids['C_ResourceList'][$R['ID']]['MarketPrice']= $R['MarketPrice'];//门票资源市场价
						$C_ids['C_ResourceList'][$R['ID']]['MaxQuantity']= $R['MaxQuantity'];//可选最大份数
						$C_ids['C_ResourceList'][$R['ID']]['MinQuantity']= $R['MinQuantity'];//可选最小份数
						$RADDdata1 = '';
						foreach($R['ResourceAddInfoList'] as $RADDdata){
							$RADDdata1.=$RADDdata['Description'];
						}
						$C_ids['C_ResourceList'][$R['ID']]['ResourceAddInfoList']= $RADDdata1;//门票附加信息列表
					}					
				}else continue 2;
			}
			$C_ids2[] = $C_ids;
		}	
		return($C_ids2);
	}
	
	//3.3门票资源价格库查询
	public function TicketResourcePriceAndInventory(){
		$this->post_array['RequestType']="TicketResourcePriceAndInventory"; 
		$reqJson=<<<H
{
    "DistributionChannel": 9, 
    "ProductID": 1600945, 
    "ResourcePriceAndInventoryRequestItemList": [
        {
            "EndDate": "2015-12-31T11:27:25", 
            "ResourceID": 3143005,
            "StartDate": "2012-7-17T11:27:25"
        }
    ]
}
H;
		$time = time();
		$this->post_array['reqJson'] = str_replace('"','\"',$reqJson);
		$this->post_array['signature'] = $this->sign($time,$this->post_array['RequestType']);
		$Ctrip_RequestData = $this->Ctrip_RequestData($time,$this->post_array);
		return $Ctrip_RequestData;
	
	}
	
	//3.4门票可订性检查
	public function TicketOrderCanBooking(){
		$this->post_array['RequestType'] = 'TicketOrderCanBooking';
		$reqJson=<<<H
{
    "DistributionChannel": 9, 
    "OrderTotalPrice": 120, 
    "PromotionList": null, 
    "ResourceCanBookingRequestItemList": [
        {
            "ResourceID": 269031, 
            "TotalPrice": 120, 
            "UseDate": "2015-05-15T22:18:05+08:00", 
            "UseQuantity": 1
        }
    ]
}
H;
		$time = time();
		$this->post_array['reqJson'] = str_replace('"','\"',$reqJson);
		$this->post_array['signature'] = $this->sign($time,$this->post_array['RequestType']);
		$Ctrip_RequestData = $this->Ctrip_RequestData($time,$this->post_array);
		return $Ctrip_RequestData;
		
	}
	
	//创建订单
	public function TicketOrderCreateForPrepay_V2($request_array){
		$this->post_array['RequestType'] = 'TicketOrderCreateForPrepay_V2';
		$Amount = $request_array['UUtnum']*$request_array['UUlprice'];
		$reqJson=<<<H
{
    "AdultNumber": "{$request_array['UUtnum']}",
    "Amount": "$Amount",
    "ClientInfoList": [     
        {
            "AgeType": "ADU",
            "BirthCity": null,
            "BirthDate": "1990-05-01T00:00:00",
            "CardCity": null,
            "ClientName": "{$request_array['pftordername']}",
            "ClientName_E": "test/test",
            "ContactInfo": "{$request_array['UUordertel']}",
            "Gender": 0,
            "HzAdd": null, 
            "HzDate": "0001-01-01T00:00:00", 
            "HzNo": "0",
            "IDCardNo": "{$request_array['IDcar']}",
            "IDCardTimelimit": "0001-01-01T00:00:00",
            "IDCardType": 1, 
            "InfoID": 0, 
            "IssueDate": "0001-01-01T00:00:00",
            "Nationality": null, 
            "PassportType": "P", 
            "VisaCountry": null    
        }
    ], 
    "DistributorOrderID": "{$request_array['pftordernum']}",
    "ContactInfo": {
        "ContactAddress": null, 
        "ContactEmail": "test@test.com", 
        "ContactFax": null, 
        "ContactMobile": "{$request_array['UUordertel']}", 
        "ContactName": "{$request_array['pftordername']}", 
        "ContactTel": null
    }, 
    "ProductInfo": {
        "ProductID": "{$request_array['ProductID']}",
    }, 
    "Remark": "特殊说明", 
    "SalesCity": 2, 
    "TicketInfo": [
        {
            "Price": "{$Amount}", 
            "TicketID": "{$request_array['TicketID']}", 
            "UseDate": "{$request_array['UUplaytime']}T23:59:59", 
            "Quantity": "{$request_array['UUtnum']}",
            "TicketType": 0
        }
    ], 
"Uid": "5474857e-65d5-48db-a98d-b82daa40333b"
}
H;
		$time = time();
		$this->post_array['reqJson'] = str_replace('"','\"',$reqJson);
		$this->post_array['signature'] = $this->sign($time,$this->post_array['RequestType']);
		$Ctrip_RequestData = $this->Ctrip_RequestData2($time,$this->post_array);
		if($Ctrip_RequestData['ResponseBody']){
			$product_data = json_decode($Ctrip_RequestData['ResponseBody'],true);
			return $product_data;
		}
		else{
			$this->logfile($request_array['pftordernum'].'|'.$Ctrip_RequestData['ErrorMessage'],'Create_fail');
			return 101;
		}
	}
	
	//查询订单
	public function SeachOrder($OrderId){
		// $OrderStartUseDate = date('Y-m-d\TH:i:s', $_SERVER['REQUEST_TIME']);
		// $timer=strtotime($OrderStartUseDate)+10*60;
		// $OrderEndUseDate = date('Y-m-d\TH:i:s',$timer);
		
		// $OrderStartUseDate = $searchTime."T00:00:00";
		// $OrderEndUseDate = $searchTime."T23:59:59"; 
		$this->post_array['RequestType'] = 'TicketSearchOrder';
		$reqJson = <<<H
{
    "OrderSearchParameter": {
        "AllianceId": {$this->post_array['AllianceID']},
        "ClientName": "",
        "OrderEndDate": "",
        "OrderEndUseDate": "",
        "OrderId": "{$OrderId}",
        "OrderStartDate": "",
        "OrderStartUseDate": "",
        "OrderStatus": null,
        "OUID": "",
        "SID": {$this->post_array['SID']},
        "Uid": ""
    },
    "PagingParameter": {
        "PageIndex": 1,
        "PageSize": 10000
    },
    "SortParameter": {
        "SortDirection": "desc",
        "SortKey": "",
        "SortType": "2"
    }
}
H;
		$time = time();
		$this->post_array['reqJson'] = str_replace('"','\"',$reqJson);
		$this->post_array['signature'] = $this->sign($time,$this->post_array['RequestType']);
		$Ctrip_RequestData = $this->Ctrip_RequestData2($time,$this->post_array);
		if($Ctrip_RequestData['ResponseBody']){
			return json_decode($Ctrip_RequestData['ResponseBody'],true);
		}else{
			return 101;
		}		
}
	//退单
	public function TicketUnsubscribeOrder($ctrip_OrderId){
		$this->post_array['RequestType'] = 'TicketUnsubscribeOrder';
		$reqJson=<<<H
{
    "DistributionChannelId": 9, 
    "OrderId": "{$ctrip_OrderId}", 
    "Reason": "", 
    "Remark": ""
}
H;
		$time = time();
		$this->post_array['reqJson'] = str_replace('"','\"',$reqJson);
		$this->post_array['signature'] = $this->sign($time,$this->post_array['RequestType']);
		$Ctrip_RequestData = $this->Ctrip_RequestData2($time,$this->post_array);
		// print_r($reqJson);
		// print_r($Ctrip_RequestData);exit;
		if($Ctrip_RequestData['ResponseBody']){
			$product_data = json_decode($Ctrip_RequestData['ResponseBody'],true);	
			if($product_data['IsSuccess'] == 'true'){
				$this->logfile($ctrip_OrderId.'|'.$product_data['IsSuccess'],'ctrip_Apply_success');
				return 100;
			}				
			else{
				$this->logfile($ctrip_OrderId.'|'.$Ctrip_RequestData['Header']['ResultMsg'],'ctrip_Apply_fail');
				return 101;
			}
		}
		else{
			$this->logfile($request_array['pftordernum'].'|'.$Ctrip_RequestData['Header']['ResultMsg'],'ctrip_Apply_fail');
			return 101;
		}
	}
	
	
	/*以下是共用函数部分*/
	public function sign($time,$RequestType){				
		$t = $time.$this->post_array['AllianceID'].strtoupper(md5($this->post_array['APIKey'])).$this->post_array['SID'].$RequestType;
		$signature = strtoupper(md5($t));
		return $signature;
	}
	
	public function Ctrip_RequestData($time,$array){
		$post_array = $this->zh_bm($array);
		$post_array =<<<h
{	
	"AllianceID":"{$post_array['AllianceID']}",
	"SID":"{$post_array['SID']}",
	"ProtocolType":"{$post_array['ProtocolType']}",
	"Signature":"{$post_array['signature']}",
	"TimeStamp":"$time",
	"Channel":"Vacations",
	"Interface":"{$post_array['RequestType']}",
	"IsError":false,
	"RequestBody":"{$post_array['reqJson']}",
	"ResponseBody":"",
	"ErrorMessage":""
}
h;
		$tmp = array(); 
		$tmp['RequestJson'] = urlencode($post_array);
		$data = "RequestJson=".$tmp['RequestJson'];
		
		$ch = curl_init();//打开
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_URL, $this->post_array['reqUri']);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		$response  = curl_exec($ch);
		curl_close($ch);//关闭 
		$date_response_ResponseBody = json_decode($response,true);
		// return $date_response_ResponseBody;
		if($date_response_ResponseBody['ResponseBody']){
			$product_data = json_decode($date_response_ResponseBody['ResponseBody'],true);
			return $product_data;
		}
		else{
			return $date_response_ResponseBody['ErrorMessage'];
		}
	}  
	
	public function Ctrip_RequestData2($time,$array){
		$post_array = $this->zh_bm($array);
		$post_array =<<<h
{	
	"AllianceID":"{$post_array['AllianceID']}",
	"SID":"{$post_array['SID']}",
	"ProtocolType":"{$post_array['ProtocolType']}",
	"Signature":"{$post_array['signature']}",
	"TimeStamp":"$time",
	"Channel":"Vacations",
	"Interface":"{$post_array['RequestType']}",
	"IsError":false,
	"RequestBody":"{$post_array['reqJson']}",
	"ResponseBody":"",
	"ErrorMessage":""
}
h;
		$tmp = array(); 
		$tmp['RequestJson'] = urlencode($post_array);
		$data = "RequestJson=".$tmp['RequestJson'];
		
		$ch = curl_init();//打开
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_URL, $this->post_array['reqUri']);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		$response  = curl_exec($ch);
		curl_close($ch);//关闭 
		$date_response_ResponseBody = json_decode($response,true);
		return $date_response_ResponseBody;
	}    	
	
	public function zh_bm($arr){  //转换编码
		 if(is_array($arr)){
			foreach($arr as $k => $v){
			 $arr[$k] = $this->zh_bm($v);
			}
		   return $arr;
		 }
		return iconv("UTF-8","GB2312//IGNORE",$arr);
	}
	
	//日志
	public function logfile($word,$path){
		$filepath= '/var/www/html/new/d/logs/api/ctrip/'.$path.'.txt';
		$word = date("Y-m-d H:i:s")."|".$word;
		if(file_exists($filepath)){
			// $word = mb_convert_encoding($word, 'GBK', 'UTF-8');
			$maxsize  = 1024*1024*10;
			$filesize = filesize($filepath);
			$filetype = end(explode(".",$filepath));
			$filename = substr($filepath,0,strpos($filepath,'.'));
			if($filesize>$maxsize)
				rename($filepath, $filename.'_'.date('YmdHis').'.'.$filetype);
		}
		$fp = fopen($filepath,"a");
		flock($fp, LOCK_EX);
		fwrite($fp,date('Y-m-d H:i:s')."|".$word."\n");
		flock($fp, LOCK_UN);
		fclose($fp);
	}
 
}
 
// $ctrip =  new Ctrip();
// $SeachOrder = $ctrip->SeachOrder("1477329150"); print_r($SeachOrder);
// $Get_lID = $ctrip->TicketSenicSpotSearch('福鼎'); //print_r($Get_lID);
// $Get_lIDs = implode(',',$Get_lID); //print_r($Get_lIDs);
// $TicketSenicSpotInfo = $ctrip->TicketSenicSpotInfo($Get_lIDs); print_r($TicketSenicSpotInfo);
//        126508,143303,110186  
/*这里需要得到TicketSenicSpotInfo的景区id，产品id，资源id 2104280*/
// $ResourcePrice = $ctrip->TicketResourcePriceAndInventory(); print_r($ResourcePrice);
// echo md5('123456');
// $TicketOrderCanBooking = $ctrip->TicketOrderCanBooking();print_r($TicketOrderCanBooking);
// $request_array  = array(
		// 'AdultNumber'=>1,
		// 'ClientName'=>'彭志萍',
		// 'ContactInfo'=>'15959110796',
		// 'IDCardNo'=>'350321199108230123',
		// 'DistributorOrderID'=>'pzp201505015001',
		// 'ContactMobile'=>'15959110796',
		// 'ContactName'=>'票付通',
		// 'ProductID'=>'1919255',
		// 'Price'=>72,
		// 'TicketID'=>'1971754',
		// 'UseDate'=>substr(date("c", strtotime("2015-05-18")),0,19),
		// 'Quantity'=>1,
		// 'Uid'=>'69433ba5-d56b-4a44-b1b8-07c9758d52cd'
// );

// echo substr(date("c", strtotime("2015-05-18")),0,19);
// echo date("Y-m-d H:i:s", strtotime("2015-05-18"));
// print_r($request_array);exit;
// $TicketOrderCreate =  $ctrip->TicketOrderCreateForPrepay_V2($request_array);
//print_r($TicketOrderCreate);

// $TicketUnsubscribeOrder = $ctrip->TicketUnsubscribeOrder();print_r($TicketUnsubscribeOrder);
?>